package com.easylinkin.linkappapi.inspection.service.impl;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.baomidou.mybatisplus.generator.config.IFileCreate;
import com.easylinkin.linkappapi.circuit.dto.RailGiveAlarmTypeConfigEnum;
import com.easylinkin.linkappapi.circuit.service.IRailGiveSystemAlarmService;
import com.easylinkin.linkappapi.common.utils.DateUtil;
import com.easylinkin.linkappapi.config.entity.SysDictItem;
import com.easylinkin.linkappapi.config.service.SysDictItemService;
import com.easylinkin.linkappapi.device.constant.DeviceConstant;
import com.easylinkin.linkappapi.device.entity.Device;
import com.easylinkin.linkappapi.device.service.DeviceService;
import com.easylinkin.linkappapi.inspection.dto.RailLinkappElectricFireRecordDTO;
import com.easylinkin.linkappapi.inspection.entity.RailLinkappElectricFireRecord;
import com.easylinkin.linkappapi.inspection.mapper.RailLinkappElectricFireRecordMapper;
import com.easylinkin.linkappapi.inspection.service.IRailLinkappElectricFireRecordService;
import com.easylinkin.linkappapi.inspection.vo.RailLinkappElectricFireRecordVO;
import com.easylinkin.linkappapi.openapi.dto.DatapushDTO;
import com.easylinkin.linkappapi.security.context.LinkappUserContextProducer;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @author lyk
 * @date 2025/6/20 上午 9:30
 */
@Service
@Slf4j
public class RailLinkappElectricFireRecordServiceImpl extends  ServiceImpl<RailLinkappElectricFireRecordMapper, RailLinkappElectricFireRecord> implements IRailLinkappElectricFireRecordService {
    @Autowired
    private SysDictItemService dictItemService;

    @Resource
    private LinkappUserContextProducer linkappUserContextProducer;
    @Autowired
    private IRailGiveSystemAlarmService railGiveSystemAlarmService;
    @Autowired
    private DeviceService deviceService;

    @Override
    public void datapushHandler(DatapushDTO datapushDTO) {
        JSONObject data = datapushDTO.getData();

        // 将查询逻辑放入主线程
        //String device_code = datapushDTO.getDevice_id();

        Device device = datapushDTO.getDevice_data_latest();
        if (Objects.isNull(device)){
            return;
        }
        if (!DeviceConstant.RailwayDeviceType.ELECTRIC_FIRE.getDescription().contains(device.getDeviceUnit().getDeviceTypeName())) {
            return;
        }
        if (Objects.isNull(device)){
            return;
        }
        // 当前累计流量
        Double activePower = data.getDouble("active_power");
        Double residualCurrent = data.getDouble("residual_current");
        Double temperature_1 = data.getDouble("temperature_1");
        Double temperature_2 = data.getDouble("temperature_2");
        Double temperature_3 = data.getDouble("temperature_3");
        Double temperature_4 = data.getDouble("temperature_4");
        if (null == activePower || null == residualCurrent || null == temperature_1
                || null == temperature_2 || null == temperature_3 || null == temperature_4) {
            return;
        }
        RailLinkappElectricFireRecord electricBoxRecord = new RailLinkappElectricFireRecord();
        electricBoxRecord.setCreateTime(new Date());
        electricBoxRecord.setDeviceCode(device.getCode());
        electricBoxRecord.setTenantId(device.getTenantId());
        electricBoxRecord.setActivePower(activePower);
        electricBoxRecord.setResidualCurrent(residualCurrent);
        electricBoxRecord.setTemperature1(temperature_1);
        electricBoxRecord.setTemperature2(temperature_2);
        electricBoxRecord.setTemperature3(temperature_3);
        electricBoxRecord.setTemperature4(temperature_4);
        baseMapper.insert(electricBoxRecord);
        /**
         * 系统告警_锚点
         */
        SysDictItem  sysDictItem = dictItemService.selectByDictItem("testing_item","4");
        if (Objects.isNull(sysDictItem)){

        }
        //剩余电量过高
        railGiveSystemAlarmService
                .datapushHandlerUseEle(datapushDTO,sysDictItem, RailGiveAlarmTypeConfigEnum.AlarmType_1);

        //温度过高
        railGiveSystemAlarmService
                .datapushHandlerUseEle(datapushDTO,sysDictItem, RailGiveAlarmTypeConfigEnum.AlarmType_2);

        //供电中断告警
        railGiveSystemAlarmService
                .datapushHandlerUseEle(datapushDTO,sysDictItem, RailGiveAlarmTypeConfigEnum.AlarmType_3);

        //电压/电流逆向序告警
        railGiveSystemAlarmService
                .datapushHandlerUseEle(datapushDTO,sysDictItem, RailGiveAlarmTypeConfigEnum.AlarmType_4);

        //ABC相警告
        railGiveSystemAlarmService
                .datapushHandlerUseEle(datapushDTO,sysDictItem, RailGiveAlarmTypeConfigEnum.AlarmType_5);
    }

    @Override
    public Map<String, Object> boxRecordByhoursOrMonthly(RailLinkappElectricFireRecordDTO railLinkappElectricFireRecord) {
        String tenantId = linkappUserContextProducer.getNotNullCurrent().getTenantId();
        railLinkappElectricFireRecord.setTenantId(tenantId);
        Map<String, Object> result = new HashMap<>();
        List<String> range = null;
        List<RailLinkappElectricFireRecord> electricBoxRecords = null;
        switch (railLinkappElectricFireRecord.getDailyOrMonthly()){
            case 0:
                //24小时
                range = DateUtil.getLast24HoursRange(DateUtil.getYYYYMMDDDate(new Date()));
                railLinkappElectricFireRecord.setStartTimeH(range.get(0));
                railLinkappElectricFireRecord.setEndTimeH(range.get(range.size()-1));
                electricBoxRecords = baseMapper.selectByDateOrTime(railLinkappElectricFireRecord);
                break;
            case 1:
                //30天
                range = DateUtil.getLast30Days();
                railLinkappElectricFireRecord.setStartTime(range.get(0));
                railLinkappElectricFireRecord.setEndTime(range.get(range.size()-1));
                electricBoxRecords = baseMapper.selectByDateOrTime(railLinkappElectricFireRecord);
                break;
            default:
                break;
        }
        if (Objects.isNull(range)){
            return result;
        }
        //遍历
        List<RailLinkappElectricFireRecord> transferStation = new ArrayList<>();
        List<Double> residualCurrentArray = new ArrayList<>();
        boolean zero = false;
        List<String> abscissa = new ArrayList<>();
        for (String  ran_Time:range){
            Double  residualCurrent = 0.00;
            if (zero) {
                residualCurrentArray.add(residualCurrent);
                abscissa.add(ran_Time);
                continue;
            }
            if (transferStation.size() == 0 ){
                int leftIndex = 0;
                int rightIndex  = electricBoxRecords.size()-1;
                while (leftIndex<=rightIndex){
                    if (leftIndex == rightIndex){
                        RailLinkappElectricFireRecord leftRecords = electricBoxRecords.get(leftIndex);
                        String leftCollectTime = DateUtil.getYYYYMMDDHHMMSSDate(leftRecords.getCreateTime());
                        if (leftCollectTime.startsWith(ran_Time)){

                            residualCurrent = (Objects.isNull(leftRecords.getResidualCurrent())?0.0:leftRecords.getResidualCurrent())+residualCurrent;
                        }else{
                            transferStation.add(leftRecords);
                        }
                        break;
                    }
                    RailLinkappElectricFireRecord leftRecords = electricBoxRecords.get(leftIndex);
                    String leftCollectTime = DateUtil.getYYYYMMDDHHMMSSDate(leftRecords.getCreateTime());
                    if (leftCollectTime.startsWith(ran_Time)){
                        residualCurrent = (Objects.isNull(leftRecords.getResidualCurrent())?0.0:leftRecords.getResidualCurrent())+residualCurrent;
                    }else{
                        transferStation.add(leftRecords);
                    }
                    leftIndex++;
                    RailLinkappElectricFireRecord rightRecords = electricBoxRecords.get(rightIndex);
                    String rightCollectTime = DateUtil.getYYYYMMDDHHMMSSDate(rightRecords.getCreateTime());
                    if (rightCollectTime.startsWith(ran_Time)){

                        residualCurrent = (Objects.isNull(rightRecords.getResidualCurrent())?0.0:rightRecords.getResidualCurrent())+residualCurrent;
                    }else{
                        transferStation.add(rightRecords);
                    }
                    rightIndex--;
                }
            }else{
                List<RailLinkappElectricFireRecord> letw = transferStation;
                transferStation = new ArrayList<>();
                int leftIndex = 0;
                int rightIndex  = letw.size()-1;
                while (leftIndex<=rightIndex) {
                    if (leftIndex == rightIndex){
                        RailLinkappElectricFireRecord leftRecords = letw.get(leftIndex);
                        String leftCollectTime = DateUtil.getYYYYMMDDHHMMSSDate(leftRecords.getCreateTime());
                        if (leftCollectTime.startsWith(ran_Time)){

                            residualCurrent = (Objects.isNull(leftRecords.getResidualCurrent())?0.0:leftRecords.getResidualCurrent())+residualCurrent;
                        }else{
                            transferStation.add(leftRecords);
                        }
                        break;
                    }
                    RailLinkappElectricFireRecord leftRecords = letw.get(leftIndex);
                    String leftCollectTime = DateUtil.getYYYYMMDDHHMMSSDate(leftRecords.getCreateTime());
                    if (leftCollectTime.startsWith(ran_Time)){

                        residualCurrent = (Objects.isNull(leftRecords.getResidualCurrent())?0.0:leftRecords.getResidualCurrent())+residualCurrent;
                    }else{
                        transferStation.add(leftRecords);
                    }
                    leftIndex++;
                    RailLinkappElectricFireRecord rightRecords = letw.get(rightIndex);
                    String rightCollectTime = DateUtil.getYYYYMMDDHHMMSSDate(rightRecords.getCreateTime());
                    if (rightCollectTime.startsWith(ran_Time)){

                        residualCurrent = (Objects.isNull(rightRecords.getResidualCurrent())?0.0:rightRecords.getResidualCurrent())+residualCurrent;
                    }else{
                        transferStation.add(rightRecords);
                    }
                    rightIndex--;
                }
            }
            if (transferStation.size() == 0) {
                zero = true;
            }
            residualCurrentArray.add(residualCurrent);
            abscissa.add(ran_Time);
        }
        result.put("electricUnit","A");
        result.put("residualCurrentArray",residualCurrentArray);
        result.put("abscissa",abscissa);
        return result;
    }

    @Override
    public Map<String, Object> temperatureLineHursOrMonthly(RailLinkappElectricFireRecordDTO railLinkappElectricFireRecordDTO) {
        String tenantId = linkappUserContextProducer.getNotNullCurrent().getTenantId();
        railLinkappElectricFireRecordDTO.setTenantId(tenantId);
        Map<String, Object> result = new HashMap<>();
        List<RailLinkappElectricFireRecord> electricBoxRecords = null;
        SimpleDateFormat sdf = null;
        switch (railLinkappElectricFireRecordDTO.getDailyOrMonthly()){
            case 0:
                //24小时
                electricBoxRecords = baseMapper.selectByTwentyFourHour(railLinkappElectricFireRecordDTO);
                sdf = new SimpleDateFormat(DateUtil.DATE_TIME_FORMAT_HM);
                break;
            case 1:
                //30天
                electricBoxRecords = baseMapper.selectByThirtyDays(railLinkappElectricFireRecordDTO);
                sdf = new SimpleDateFormat(DateUtil.DATE_TIME_FORMAT_DAY);
                break;
            default:
                break;
        }
        List<Double> temperature_1_array = new ArrayList<>();
        List<Double> temperature_2_array = new ArrayList<>();
        List<Double> temperature_3_array = new ArrayList<>();
        List<Double> temperature_4_array = new ArrayList<>();
        boolean zero = false;
        List<String> abscissa = new ArrayList<>();
        for (RailLinkappElectricFireRecord fireRecord:electricBoxRecords){
            String abscissa_str = sdf.format(fireRecord.getCreateTime());
            temperature_1_array.add(fireRecord.getTemperature1());
            temperature_2_array.add(fireRecord.getTemperature2());
            temperature_3_array.add(fireRecord.getTemperature3());
            temperature_4_array.add(fireRecord.getTemperature4());
            abscissa.add(abscissa_str);
        }
        result.put("tempUnit","°C");
        result.put("temperature_1_array",temperature_1_array);
        result.put("temperature_2_array",temperature_2_array);
        result.put("temperature_3_array",temperature_3_array);
        result.put("temperature_4_array",temperature_4_array);
        result.put("abscissa",abscissa);
        return result;
    }

    @Override
    public List<RailLinkappElectricFireRecordVO> codeByNewRecords(String tenantId, List<String> codes) {
        return baseMapper.codeByNewRecords(tenantId,codes);
    }
}
